package com.app.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.app.common.Api;
import com.app.entity.User;
import com.app.service.UserService;
import com.app.vo.req.LoginReq;
import com.app.vo.req.Register;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("login")
    public Api login(@RequestBody  @Valid  LoginReq loginReq) {
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(StrUtil.isNotBlank(loginReq.getUsername()), User::getUsername, loginReq.getUsername()));
        if (StrUtil.equals(user.getPassword(), SecureUtil.sha1(loginReq.getPassword()))) {
            return Api.ok(MapUtil.of("token", "123456"), "登录成功");
        }
        return Api.fail("密码错误");
    }

    @PostMapping("register")
    public Api register(@RequestBody @Valid Register register) {
        if (userService.exists(Wrappers.<User>lambdaQuery().eq(StrUtil.isNotBlank(register.getUsername()), User::getUsername, register.getUsername()))) {
            return Api.fail("用户名已存在");
        }
        User user = BeanUtil.copyProperties(register, User.class);
        user.setPassword(SecureUtil.sha1(user.getPassword()));
        userService.save(user);
        return Api.ok();
    }

    @GetMapping("test")
    public String test() {
        return "test";
    }

    @GetMapping("test1")
    public int test1() {
        return 1;
    }

    @GetMapping("test2")
    public boolean test2() {
        return true;
    }

    @GetMapping("add")
    public void add() {
    }
}
